package com.coder520.remoteservicetest;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.coder520.remoteservicestudy.IStudentManager;
import com.coder520.remoteservicestudy.Student;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private IStudentManager mStudentManagerService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent();
        intent.setClassName("com.coder520.remoteservicestudy",
                "com.coder520.remoteservicestudy.StudentManagerService");
        bindService(intent, mServiceConnect, BIND_AUTO_CREATE);
    }

    private ServiceConnection mServiceConnect = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mStudentManagerService = IStudentManager.Stub.asInterface(service);
            try {
                mStudentManagerService.addStudent(new Student(3, "张三", 20));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                mStudentManagerService.addStudent(new Student(4, "李四", 40));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                Log.d(TAG, "coder 520....students size is :"
                        + mStudentManagerService.getStudentCount());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                mStudentManagerService.deleteStudent(3);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                Log.d(TAG, "coder 520....students size is :"
                        + mStudentManagerService.getStudentCount());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                List<Student> allStudents = mStudentManagerService.getAllStudent();
                for (Student student : allStudents) {
                    Log.d(TAG, "coder 520....student :" + student);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mStudentManagerService = null;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnect);
    }
}
